#example 1 - read file

def readfile():
    file = open('plik.txt')
    try:
        text = file.read()
    finally:
        file.close()
    print text

#example 2   line:    line of file
#            what:    text to replace
#            on_what: target text

def changeline(line, what, on_what):
    
    source      = open('plik.txt').readlines() #this return list witch each line
    print source
    target      = open('plik.txt', 'w')
    counterLine = 1

    for s in source:
        
        if counterLine == int(line):
            target.write(s.replace(what, on_what))
        else:
            target.write(s)
            
        counterLine = counterLine + 1

    target.close()

#example 3
    
def countLineOfFile(file):
    count = len(open(file, 'r').readlines())
    print count

countLineOfFile("plik.txt")
changeline(3,"3", "new_line")
readfile()

#example 4 - write in file in binary mode - ignore \n

fo = open("foo1.txt", "wb")

print "Name of the file: ", fo.name
print "Closed or not   : ", fo.closed
print "Opening mode    : ", fo.mode

fo.write("abc\nabc")
fo.close

#example 5 - write in file in default mode
fo = open("foo.txt", "w")

print "Name of the file: ", fo.name
print "Closed or not   : ", fo.closed
print "Opening mode    : ", fo.mode

fo.write("abc\nabc")
fo.close

#example 5 - Yield & with descriptor

from collections import deque

def search (lines, pattern, history = 1):
    prev = deque(maxlen = history)
    for line in lines:
        if pattern in line:
            yield line, prev
        print prev
        prev.append(line)

with open("withFile.txt") as f:
    for line, prev in search(f, "python", 1):
        for pline in prev:
            print (pline)
        print (line)
        print ('-'*20)
                             
    

